package xmlcollabclient.staro;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;

/**
 *
 * @author Sasa
 */
public class Protocol {

    // socket
    String serverAddress = "localhost";
    Integer serverPort = 9876;
    Socket socket;
    DataOutputStream bw;


    public Protocol() throws Exception {
        this.socket = openSocket(this.serverAddress, this.serverPort);
        this.bw = writer(this.socket);
    }

    public Boolean logIn(String username, String password) throws Exception {
       this.send("LOGIN\r\n");
       this.send("USERNAME:" + username +"\r\n");

        return false;
    }



    public void send(String msg) throws Exception {
        msg = msg + "\n";
        this.bw.writeBytes(msg);


        this.bw.flush();
        //this.socket.close();
    }
    public void closeSocket() throws Exception {
        this.socket.close();
    }

    private static DataOutputStream writer(Socket socket) throws Exception {
        DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
        return dos;
    }

    private static Socket openSocket(String server, Integer port) throws Exception {
        InetAddress inteAddress = InetAddress.getByName(server);
        SocketAddress socketAddress = new InetSocketAddress(inteAddress, port);

        Socket socket = new Socket();
        socket.connect(socketAddress);

        return socket;
    }
}